<?php

namespace app\common\library\elasticsearch;

use Elastic\Elasticsearch\Client;
use \Elastic\Elasticsearch\ClientBuilder;
use Elastic\Elasticsearch\Exception\AuthenticationException;

class EsClient
{
    /**
     * 获取客户端
     * @return Client
     * @throws AuthenticationException
     */
    public function getClient(): Client
    {
        $config = config('elasticsearch');
        $client = ClientBuilder::create()
            ->setHosts([$config['endpoint']])
            ->setSSLVerification(false);
        if ($config['api_key'] && $config['api_encoded']) {
            $client->setApiKey($config['api_key'], $config['api_id']);
        } elseif ($config['username'] && $config['password']) {
            $client->setBasicAuthentication($config['username'], $config['password']);
        }
        return $client->build();
    }
}